﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Jayden.Dll.BitTorrent
{
	public class BitTorrentFileManager
	{
		private byte[] m_PeerId;
		private BitTorrentFile m_BitTorrentFile;
		private List<BitTorrentPeer> m_Peers;
		private BitTorrentPiece[] m_BitField;

		private long m_TotalLength = 0;
		private long m_Downloaded = 0;
		private long m_Uploaded = 0;
		private long m_Left = 0;

		public BitTorrentFileManager(byte[] peerId, BitTorrentFile file)
		{
			m_PeerId = peerId;
			m_BitTorrentFile = file;
			m_Peers = new List<BitTorrentPeer>();

			if (file.IsSingleFileMode)
				m_TotalLength = file.Length;
			else
			{
				for (int c = 0; c < file.MultipleFilesCount; c++)
					m_TotalLength += file.GetFileLength(c);
			}
			m_Left = m_TotalLength;

			m_BitField = new BitTorrentPiece[file.PiecesCount];
			for (int c = 0; c < m_BitField.Length; c++)
				m_BitField[c] = new BitTorrentPiece(this, c);
		}

		public byte[] PeerId { get { return m_PeerId; } }
		public BitTorrentFile File { get { return m_BitTorrentFile; } }
		public long TotalLength { get { return m_TotalLength; } }
		public long Downloaded { get { return m_Downloaded; } }
		public long Uploaded { get { return m_Uploaded; } }
		public long Left { get { return m_Left; } }

		public int GetPieceLength(int index)
		{
			return  index < m_BitTorrentFile.PiecesCount - 1 ? m_BitTorrentFile.PieceLength : (int)(m_TotalLength % m_BitTorrentFile.PieceLength);
		}

		public void OnBitTorrentPeerReceived(BitTorrentPeerProvider provider, List<BitTorrentPeer> peers)
		{
			foreach (BitTorrentPeer peer in peers)
			{
				peer.Connect();
				Thread.Sleep(500);
				m_Peers.Add(peer);
			}
		}
	}
}
